<?php

namespace App\Http\Middleware;

use App\Models\System\Rolepower;
use Closure;

class CheckPower
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$menu_id)
    {
        $role_id = auth()->user()->cur_role_id;
        if(!$role_id){
            return redirect()->route('apps.disable')->with('error','没有权限');
        }

        $powers = session('menuroles');

        if(!$powers || !isset($powers[$role_id])){
            $menus = Rolepower::where('role_id',$role_id)->pluck('actionid')->toArray();
            session(['menuroles' => [$role_id => $menus]]);
            $powers = [$role_id => $menus];
        }
        $menu_id = explode('|',$menu_id);
        if(count($menu_id) == 1){
            $menu_id = $menu_id[0];
            if(!isset($powers[$role_id]) || !in_array($menu_id,$powers[$role_id])){
                return redirect()->route('apps.disable')->with('error','没有权限');
            }
        }else if(count($menu_id) > 1){
            $t = false;
            foreach($menu_id as $id){
                if(isset($powers[$role_id]) && in_array($id,$powers[$role_id])){
                    $t = true;
                    break;
                }
            }
            if(!$t){
                return redirect()->route('apps.disable')->with('error','没有权限');
            }
        }

        return $next($request);
    }
}
